import { useCookies } from '@vueuse/integrations/useCookies'
import { useBrowserLocation, useStorage } from '@vueuse/core'
import secret from './secret'
import config from '../config'
import { UserInfoType, AccountType } from '@type'

const cookies = useCookies([config.CookTokenName, config.CookUserIdName])
const storageUserInfo = useStorage<UserInfoType>(config.CookUserInfoName, {})
const storageAccunt = useStorage(config.CookAccountName, "")

/**
 * 获取域名
 * @param count Number 要截取的域名级， 由后到前数
 * @return 操作之后的完整域名
*/
const getServeName = (count: number = 0): string => {
  const location = useBrowserLocation()
  const hostname = location.value.hostname || ""
  if (hostname !== "localhost") {
    const str = hostname.split('.').slice(count).join('.')
    return count ? '.' + str : str 
  }
  return hostname
}

/**
 * @param token string
 * @return boolean | void 存储成功返回 true
 * 如果第一个参数为空择执行删除 tooken 操作
 */
export const setToken = (token?: string, userId?: string): boolean | void => {
  const hostname = getServeName(2)
  const time = Date.now() + ((24 * 60 * 60 * 1000) * (config.cookieExpires + 1))
  const expires: Date = new Date(time)
  //  把cookie中存储token的名字后加上 userId 为key 进行重新存储
  const name = config.CookTokenName +'_'+ (userId || cookies.get(config.CookUserIdName))

  if (token) {
    cookies.set(name, secret.Encrypt(token), {expires: expires, domain: hostname})
  } else {
    cookies.remove(name, {domain: hostname})
    cookies.remove(config.CookUserIdName, {domain: hostname})
  }
}
/**
 * @param name string
 * @return string 返回对应用户 userId 的 token
 */
export const getToken = (name: string = config.CookTokenName): string => {
  const _name = name +'_'+ cookies.get(config.CookUserIdName)
  const _token = cookies.get(_name)
  return _token ? secret.Decrypt(_token) : ""
}
/**
 * @param name string
 * @return any 返回对应用户 user info
 */
export const getUserInfo = (name: string = config.CookUserInfoName): UserInfoType => {
  return storageUserInfo.value
}
/** 
 * 在sotrage中存储用户信息，并同时进行 token 的设值
 * @param info object
 * @param token string
 */
export const setUserInfo = (info?: UserInfoType, token?:string): void => {
  if (info) {
    storageUserInfo.value = info
    cookies.set(config.CookUserIdName, info.userId)
    token && setToken(token, info.userId)
  } else {
    storageUserInfo.value = {}
  }
}

export const getUserId = (): string => {
  return cookies.get<string>(config.CookUserIdName)
}
/** 
 * 在 storage 中存储账户登录信息
 * @param account AccountType
 */
export const setAccount = (account: AccountType): void => {
  const hasAccount = Object.keys(account).length
  if(hasAccount) {
    const accountStr = [account.UserName, account.PassWord, account.isRemember].join('=>')
    storageAccunt.value = secret.Encrypt(accountStr)
  }else{
    storageAccunt.value = ""
  }
}
/** 
 * 获取登录账号信息
 * @return account AccountType
 */
export const getAccount = (): AccountType => {
  const account = secret.Decrypt(storageAccunt.value)
  if(account.indexOf('=>') != -1) {
    return {
      UserName: account.split('=>')[0],
      PassWord: account.split('=>')[1],
      isRemember: account.split('=>')[2],
    }
  }
  return {UserName: "", PassWord: "", isRemember: false}
}